import React, { memo, useCallback, useState, useMemo } from 'react';
import { List, Checkbox, Button, Space, Pagination, Spin, Empty as AntEmpty } from 'antd';
import { PlusOutlined, SelectOutlined } from '@ant-design/icons';
import type { ICourseListProps } from '@/types/components/course';
import type { ICourse } from '@/types/course';
import CourseCard from '../CourseCard';
import { Empty } from '@/components/common';
import styles from './CourseList.module.css';

/**
 * 课程列表组件
 * @description 用于显示课程列表，支持分页、选择、批量操作等功能
 */
const CourseList: React.FC<ICourseListProps> = memo(({
  courses,
  categories,
  loading = false,
  onEdit,
  onDelete,
  onViewDetail,
  onSelect,
  selectedCourseIds = [],
  selectable = false,
  className,
  emptyText = '暂无课程数据'
}) => {
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(12);

  // 计算分页数据
  const paginatedData = useMemo(() => {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    return courses.slice(startIndex, endIndex);
  }, [courses, currentPage, pageSize]);

  // 处理单个课程选择
  const handleCourseSelect = useCallback((courseId: string, selected: boolean) => {
    if (!onSelect) return;

    let newSelectedIds: string[];
    if (selected) {
      newSelectedIds = [...selectedCourseIds, courseId];
    } else {
      newSelectedIds = selectedCourseIds.filter(id => id !== courseId);
    }
    onSelect(newSelectedIds);
  }, [selectedCourseIds, onSelect]);

  // 处理全选/取消全选
  const handleSelectAll = useCallback((checked: boolean) => {
    if (!onSelect) return;

    if (checked) {
      const allIds = paginatedData.map(course => course.id);
      const newSelectedIds = [...new Set([...selectedCourseIds, ...allIds])];
      onSelect(newSelectedIds);
    } else {
      const currentPageIds = paginatedData.map(course => course.id);
      const newSelectedIds = selectedCourseIds.filter(id => !currentPageIds.includes(id));
      onSelect(newSelectedIds);
    }
  }, [paginatedData, selectedCourseIds, onSelect]);

  // 处理页码变化
  const handlePageChange = useCallback((page: number, size?: number) => {
    setCurrentPage(page);
    if (size && size !== pageSize) {
      setPageSize(size);
    }
  }, [pageSize]);

  // 计算选择状态
  const selectState = useMemo(() => {
    const currentPageIds = paginatedData.map(course => course.id);
    const selectedInCurrentPage = currentPageIds.filter(id => selectedCourseIds.includes(id));
    
    return {
      indeterminate: selectedInCurrentPage.length > 0 && selectedInCurrentPage.length < currentPageIds.length,
      checked: currentPageIds.length > 0 && selectedInCurrentPage.length === currentPageIds.length,
      selectedCount: selectedCourseIds.length
    };
  }, [paginatedData, selectedCourseIds]);

  // 渲染列表头部
  const renderListHeader = () => {
    if (!selectable) return null;

    return (
      <div className={styles.listHeader}>
        <div className={styles.selectSection}>
          <Checkbox
            indeterminate={selectState.indeterminate}
            checked={selectState.checked}
            onChange={(e) => handleSelectAll(e.target.checked)}
          >
            全选当前页
          </Checkbox>
          {selectState.selectedCount > 0 && (
            <span className={styles.selectedCount}>
              已选择 {selectState.selectedCount} 个课程
            </span>
          )}
        </div>
        
        {selectState.selectedCount > 0 && (
          <Space>
            <Button
              size="small"
              icon={<SelectOutlined />}
              onClick={() => onSelect?.([])}
            >
              清空选择
            </Button>
          </Space>
        )}
      </div>
    );
  };

  // 渲染空状态
  const renderEmpty = () => (
    <div className={styles.emptyContainer}>
      <Empty
        description={emptyText}
        showAction={true}
        actionText="添加课程"
        onAction={() => {
          // 这里可以触发添加课程的操作
          console.log('添加课程');
        }}
      />
    </div>
  );

  // 渲染课程卡片
  const renderCourseCard = (course: ICourse) => (
    <div key={course.id} className={styles.cardWrapper}>
      <CourseCard
        course={course}
        categories={categories}
        onEdit={onEdit ? (id: string) => onEdit(courses.find(c => c.id === id)!) : undefined}
        onDelete={onDelete}
        onViewDetail={onViewDetail}
        selectable={selectable}
        selected={selectedCourseIds.includes(course.id)}
        onSelect={handleCourseSelect}
        showActions={true}
      />
    </div>
  );

  if (loading) {
    return (
      <div className={styles.loadingContainer}>
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }

  if (courses.length === 0) {
    return renderEmpty();
  }

  return (
    <div className={`${styles.courseList} ${className || ''}`}>
      {renderListHeader()}
      
      <div className={styles.listContent}>
        <div className={styles.cardGrid}>
          {paginatedData.map(renderCourseCard)}
        </div>
      </div>

      {courses.length > pageSize && (
        <div className={styles.paginationContainer}>
          <Pagination
            current={currentPage}
            pageSize={pageSize}
            total={courses.length}
            onChange={handlePageChange}
            onShowSizeChange={handlePageChange}
            showSizeChanger
            showQuickJumper
            showTotal={(total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
            }
            pageSizeOptions={['12', '24', '48', '96']}
          />
        </div>
      )}
    </div>
  );
});

CourseList.displayName = 'CourseList';

export default CourseList;